/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');
var TgDesignPcModel = require('./TgDesignPcModel');

var async  = require( 'async'); // 同步控制

// Schema 结构
var TgDesignPageModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`page_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '设计模板页ID',
  //`design_id` bigint(20) unsigned NOT NULL COMMENT '设计模板ID',
  //`map_page_id` bigint(20) unsigned NOT NULL COMMENT '来源 模板页ID',
  //`page_index` int(3) NOT NULL DEFAULT '0' COMMENT '页下标（0开始）',
  //`backup_flg` int(1) NOT NULL DEFAULT '0' COMMENT '0普通页; 1保留页',
  //`data` mediumtext COMMENT '模版页内容',
  //`hash_tag` varchar(100) DEFAULT '0' COMMENT '标记',
  //`thumb` text,
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0',


};
TgDesignPageModel.prototype = new ItbBaseModel();

// 取得表名
TgDesignPageModel.prototype.getTableName = function(){
    return 'tg_design_page';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
TgDesignPageModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'page_id='+this.page_id;
}

// 取得排序方法（需要各派生类进行重载）
TgDesignPageModel.prototype.getOrderBy = function(){
    return ' page_index asc ';
}

//------------------------------------------------------------------
/* 获取分页page信息
 * 参数:design_id/page_id
 * 参数:callback:回调
 * */
TgDesignPageModel.prototype.getPageInfoById = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' select t.page_id, t.design_id, t.map_page_id, t.page_index, t.backup_flg, '+
            ' t.data, t.hash_tag, t.thumb '+
            ' from TG_DESIGN_PAGE t'+
            ' where t.del_flg = 0 ';
        if(THIS.design_id){
            sql += ' and t.design_id = '+ THIS.design_id;
        }
        if(THIS.page_id){
            sql += ' and t.page_id = '+ THIS.page_id;
        }
        sql += ' order by t.design_id, t.page_index ';

        //var sqlValue = [THIS.type_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();

            callback(error, result);
        });
    });
}
//------------------------------------------------------------------

//------------------------------------------------------------------
/**
 * 批量新规/更新pages
 * @param arrPageJson
 * @param bNewFlg
 * @param callback: 返回值格式
 *       [{
 *          page_id: 1,
 *          pc: [2,3,4]
 *       }]
 */
TgDesignPageModel.prototype.updatePages = function(callback,arrPageJson,bNewFlg){
    var THIS = this;

    var asyncFuncs = [];
    for (var i in arrPageJson) {

        asyncFuncs.push((function (index, pageJson) {
            return function (asyncCallback) {

                if (bNewFlg) {
                    // 新建page
                    var entity = new TgDesignPageModel({
                        design_id: THIS.design_id,
                        map_page_id: pageJson.page_id,// *
                        page_index: pageJson.page_index,
                        backup_flg: pageJson.backup_flg,
                        data: pageJson.data,
                        hash_tag: pageJson.hash_tag,
                        thumb: null,// TODO
                        update_by: THIS.user_id,
                    });
                    entity.saveToDB(function(error, newPageId){
                        if(error){
                            console.log('TgDesignPageModel.js [updatePages] savePage ERR: '+error);
                            return asyncCallback(error, null);
                        }
                        var ret = {
                            page_index: pageJson.page_index,
                            page_id: newPageId
                        };

                        // 新建pc
                        var subAsyncFuncs = [];
                        for(var j in pageJson.pcData) {
                            subAsyncFuncs.push((function (idx, pcJson) {
                                return function(subCallback) {
                                    var pcEnt = new TgDesignPcModel({
                                        design_id: THIS.design_id,
                                        page_id: newPageId,
                                        pc_index: pcJson.pc_index,
                                        backup_flg: pcJson.backup_flg,
                                        data: pcJson.data,
                                        replaces: pcJson.replaces,
                                        hash_tag: pcJson.hash_tag,
                                        thumb_s: null,// TODO
                                        update_by: THIS.user_id,
                                    });
                                    pcEnt.saveToDB(function(err, newPcId) {
                                        if (err) {
                                            console.log('TgDesignPageModel.js [updatePages] savePC ERR: ' + err);
                                            return subCallback(err, null);
                                        }
                                        var subRet = {
                                            pc_index: pcJson.pc_index,
                                            pc_id: newPcId
                                        };
                                        return subCallback(null, subRet);
                                    });
                                }
                            })(j, pageJson.pcData[j]));
                        }
                        async.parallel(subAsyncFuncs, function (subErr, results) {
                            if(subErr) {
                                return asyncCallback(subErr, null);
                            }
                            var subRet = results.sort(function(a,b){
                                return a.pc_index - b.pc_index;
                            });
                            var subRetIds = [];
                            for (var m in subRet){
                                subRetIds.push(subRet[m].pc_id);
                            }
                            ret.pc=subRetIds;

                            return asyncCallback(null, ret);
                        });

                    });

                } else {
                    // 更新page
                    var updEnt = new TgDesignPageModel({
                        page_id: pageJson.page_id,
                        page_index: pageJson.page_index,
                        backup_flg: pageJson.backup_flg,
                        data: pageJson.data,
                        hash_tag: pageJson.hash_tag,
                        thumb: null,
                        update_by: THIS.user_id,
                        del_flg: 0,// 更新时恢复删除状态
                    });
                    updEnt.updateToDB(function(error2, rets2){
                        if(error2){
                            console.log('TgDesignPageModel.js [updatePages] UpdPage Err: '+error2);
                            return asyncCallback(error2, null);
                        }
                        var ret = {
                            page_index: pageJson.page_index,
                            page_id: pageJson.page_id
                        };

                        // 更新pc
                        var subAsyncFuncs2 = [];
                        for(var j in pageJson.pcData) {
                            subAsyncFuncs2.push((function (idx, pcJson) {
                                return function(subCallback) {
                                    var pcUpdEnt = new TgDesignPcModel({
                                        pc_id: pcJson.pc_id,
                                        pc_index: pcJson.pc_index,
                                        backup_flg: pcJson.backup_flg,
                                        data: pcJson.data,
                                        replaces: pcJson.replaces,
                                        hash_tag: pcJson.hash_tag,
                                        update_by: THIS.user_id,
                                    });
                                    pcUpdEnt.updateToDB(function(err, rets) {
                                        if (err) {
                                            console.log('TgDesignPageModel.js [updatePages] UpdPC ERR: ' + err);
                                            return subCallback(err, null);
                                        }
                                        var subRet = {
                                            pc_index: pcJson.pc_index,
                                            pc_id: pcJson.pc_id
                                        };
                                        return subCallback(null, subRet);
                                    });
                                }
                            })(j, pageJson.pcData[j]));
                        }
                        async.parallel(subAsyncFuncs2, function (subErr, results) {
                            if(subErr) {
                                return asyncCallback(subErr, null);
                            }
                            var subRet = results.sort(function(a,b){
                                return a.pc_index - b.pc_index;
                            });
                            var subRetIds = [];
                            for (var m in subRet){
                                subRetIds.push(subRet[m].pc_id);
                            }
                            ret.pc=subRetIds;

                            return asyncCallback(null, ret);
                        });

                    });
                }
            }
        })(i, arrPageJson[i])); // 利用闭包解决动态参数传递问题
    }
    async.parallel(asyncFuncs, function (err, results) {
        if(err) {
            return callback(err, null);
        }

        var ret = results.sort(function(a,b){
            return a.page_index - b.page_index;
        });
        var retIds = [];
        for (var i in ret){
            retIds.push({
                pageId: ret[i].page_id,
                pcIds: ret[i].pc||[]
            });
        }

        return callback(null, retIds);
    });
}
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 根据design_id/page_id获取page信息
 * 参数:callback:回调
 */
TgDesignPageModel.prototype.getPageInfoById = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('TgDesignPageModel.getPageInfoById Err:'+err);
        }
        // Use the connection
        var sql = ' SELECT * FROM TG_DESIGN_PAGE t WHERE t.del_flg = 0 ';
        if(THIS.design_id) {
            sql += ' AND t.design_id =' + THIS.design_id;
        }
        if(THIS.page_id){
            sql += ' AND t.page_id =' + THIS.page_id;
        }
        sql+=' ORDER BY t.design_id, t.page_index ';

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        //console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();
            callback(error, result);
        });
    });
}
//------------------------------------------------------------------

// 导出
module.exports = TgDesignPageModel;